package love.yuanmengrobot.qianyugarden.service.impl;

import love.yuanmengrobot.qianyugarden.dao.*;
import love.yuanmengrobot.qianyugarden.entity.*;
import love.yuanmengrobot.qianyugarden.service.BookService;
import love.yuanmengrobot.qianyugarden.utils.Events;
import love.yuanmengrobot.qianyugarden.utils.ParamReceive;
import love.yuanmengrobot.qianyugarden.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 书籍(Book)表服务实现类
 *
 * @author makejava
 * @since 2021-07-13 14:28:10
 */
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;
    @Autowired
    private BookEventDao bookEventDao;
    @Autowired
    private BookLabelsDao bookLabelsDao;

    @Autowired
    private UserEventsDao userEventsDao;

    @Autowired
    private FavoritesDao favoritesDao;

    @Override
    public List<ThousandLanguage> getAllLanguage() {
        return bookDao.getAllLanguage();
    }

    @Override
    public BookEventAbook queryByBookId(String bookId) {
        return bookDao.queryByBookId(bookId);
    }


    /**
     * 通过ID查询单条数据
     *
     * @param objectid 主键
     * @return 实例对象
     */
    @Override
    public BookAuser queryById(String objectid) {
        return this.bookDao.queryById(objectid);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<BookEventAbook> queryAllByLimit(int offset, int limit) {
        return this.bookDao.queryAllByLimit(offset, limit);
    }

    @Override
    public int queryAllBooksCount(String userid) {
        return bookDao.queryAllBooksCount(userid);
    }

    @Override
    public void likeEvents(String bookId, int result) {
        bookDao.likeEvents(bookId,result);
    }

    @Override
    public void observationEvents(String bookId, int result) {
        bookDao.observationEvents(bookId,result);
    }

    @Override
    public void collectionEvents(String bookId, int result) {
        bookDao.collectionEvents(bookId,result);
    }

    @Override
    public void downloadEvents(String bookId, int result) {
        bookDao.downloadEvents(bookId,result);
    }

    @Override
    public List<BookEventAbook> queryBookByAllConstraint(ParamReceive params) {
        return bookDao.queryBookByAllConstraint(params);
    }

    @Override
    public List<Book> queryAllbookByLimit(String userid,int offset, int limit){
        return bookDao.queryAllbookByLimit(userid,offset,limit);
    }

    //业务处理
    @Override
    public Map processService(ParamReceive params) {
        int offset=params.getOffset()==null ? 0 : params.getOffset();//默认不传参时
        int limit=params.getLimit()==null ? 6 : params.getLimit();//默认不传参时
        String language=params.getLanguage()==null ? "综合" : params.getLanguage();
        String order=params.getOrder()==null? "综合排序": params.getOrder();
        String size=params.getSize()==null? "全部大小": params.getSize();
        String time=params.getTime()==null? "全部时间": params.getTime();
        params.setOffset(offset);
        params.setLimit(limit);
        params.setLanguage(language);
        params.setSize(size);
        params.setTime(time);
        switch(order){
            case "点击最多": params.setOrder("observations");break;
            case "点赞最多": params.setOrder("likes");break;
            case "下载最多": params.setOrder("downloads");break;
            case "收藏最多": params.setOrder("collections");break;
        }
        List<BookEventAbook> bookList =null;
        if("综合排序".equals(order)){
            bookList=bookDao.queryBookByNoOrder(params);
        }else{
            bookList=bookDao.queryBookByAllConstraint(params);
        }
        int booksCount = bookDao.queryBooksCountByAllConstraint(params);
        Map container=new HashMap<String,Object>();
        container.put("bookList",bookList);
        container.put("booksCount",booksCount);
        container.put("offset",offset);
        container.put("limit",limit);
        container.put("language",language);
        container.put("order",order);
        container.put("size",size);
        container.put("time",time);
        return container;
    }

    @Override
    public Map userEventProcess(User user, String bookId) {

        Map contain=new HashMap<String,Object>();
        //同一用户在一天内多次浏览同一本书，该书的浏览次数仅算一次
        UserEvents userEvents=new UserEvents();
        userEvents.setEventtype("浏览历史");
        userEvents.setTargetid(bookId);
        userEvents.setUserid(user.getObjectid());
        Date date = userEventsDao.queryTimeByConstraint(userEvents);
        if(date==null || new Date().getDay()-date.getDay()>=1){
            observationEvents(bookId,1);
        }

        //该用户是否点过赞
        userEvents.setEventtype("点赞");
        List<UserEvents> likesList = userEventsDao.queryAll(userEvents);
        if(likesList.size()==0){
            contain.put("likeStatus","no like");
        }else{
            contain.put("likeStatus","haven like");
        }

        //该用户是否收藏过该book
        userEvents.setEventtype("收藏");
        List<UserEvents> collectionList = userEventsDao.queryAll(userEvents);
        if(collectionList.size()==0){
            contain.put("collectionStatus","no collection");
        }else{
            contain.put("collectionStatus","haven collection");
        }

        //用户浏览历史不受时间限制
        userEvents.setEventtype("浏览历史");
        userEvents.setObjectid(RandomUtils.createIdOX("UE"));
        userEvents.setOperationstatus("成功");
        userEvents.setCreatetime(RandomUtils.getTime());
        userEventsDao.insert(userEvents);

        return contain;
    }

    @Override
    public Map userEvents(User user, Events events) {
        Map contain=new HashMap<String,Object>();
        UserEvents userEvents=new UserEvents();
        userEvents.setEventtype(events.getEventType());
        userEvents.setUserid(user.getObjectid());
        userEvents.setTargetid(events.getValue());
        if("下载".equals(events.getEventType())){
            userEvents.setObjectid(RandomUtils.createIdOX("UE"));
            userEvents.setOperationstatus("成功");
            userEvents.setCreatetime(RandomUtils.getTime());
            userEventsDao.insert(userEvents);
            downloadEvents(events.getValue(),1);//book下载次数+1
            contain.put(events.getEventType()+"Status","download successful");
        }else if("点赞".equals(events.getEventType())){
            //查询该用户是否点过赞
            List<UserEvents> userEventsList = userEventsDao.queryAll(userEvents);
            //未点过赞则插入一条事件进入user_events
            if(userEventsList.size()==0){
                userEvents.setObjectid(RandomUtils.createIdOX("UE"));
                userEvents.setOperationstatus("成功");
                userEvents.setCreatetime(RandomUtils.getTime());
                userEventsDao.insert(userEvents);
                likeEvents(events.getValue(),1);
                contain.put(events.getEventType()+"Status","like successful");
            }else{
                contain.put(events.getEventType()+"Status","haven like");
            }
        }else if("收藏".equals(events.getEventType())){
            List<UserEvents> collectionList = userEventsDao.queryAll(userEvents);
            //未收藏过该book
            if(collectionList.size()==0){
                userEvents.setObjectid(RandomUtils.createIdOX("UE"));
                userEvents.setOperationstatus("成功");
                userEvents.setCreatetime(RandomUtils.getTime());
                userEventsDao.insert(userEvents);//添加用户事件
                Favorites favorites=new Favorites();
                favorites.setObjectid(RandomUtils.createIdOX("FA"));
                favorites.setUserid(user.getObjectid());
                favorites.setFavoritename("默认收藏夹");
                favorites.setRelationid(events.getValue());
                favorites.setParentid(null);
                favoritesDao.insert(favorites);//添加收藏夹
                collectionEvents(events.getValue(),1);
                contain.put(events.getEventType()+"Status","collection successful");
            }else{
                contain.put(events.getEventType()+"Status","haven collection");
            }
        }
        return contain;
    }

    /**
     * 新增数据
     *
     * @param book 实例对象
     * @return 实例对象
     */
    @Override
    public Book insert(Book book) {
        this.bookDao.insert(book);
        return book;
    }


    /**
     * 新增数据,并且新增对应的标签、事件
     *
     * @param book 实例对象
     * @return 实例对象
     */
    public Book insertAndLabelAndEvent(Book book, BookLabels[] bookLabels, BookEvent bookEvent) {
        this.bookDao.insertAndID(book);
        for (BookLabels b : bookLabels) {
            if (b == null) continue;
            this.bookLabelsDao.insertAndID(b);
        }
        this.bookEventDao.insertAndID(bookEvent);

        return book;
    }

    ;


    /**
     * 修改数据
     *
     * @param book 实例对象
     * @return 实例对象
     */
    @Override
    public Book update(Book book) {
        this.bookDao.update(book);
        return this.queryById(book.getObjectid());
    }

    /**
     * 通过主键删除数据
     *
     * @param objectid 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String objectid) {
        return this.bookDao.deleteById(objectid) > 0;
    }

}
